package cn.cloud9.designpattern.dp05proxy.proxy_03_jdk_dynamic.proxy_pack;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @projectName: Java
 * @author: Cloud9
 * @date: 2022年05月23日 16:21
 * @version: 1.0
 */
public class MyClassLoader extends ClassLoader {
    private File classPathFile;

    public MyClassLoader() {
        String path = this.getClass().getResource("").getPath();
        this.classPathFile = new File(path);
    }

    @Override
    protected Class<?> findClass(String name) {

        final String className = this.getClass().getPackage().getName() + "." + name;
        if (this.classPathFile == null) return null;

        FileInputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            // G:\design-pattern\Java\target\classes\cn\cloud9\designpattern\dp05proxy\proxy_03_jdk_dynamic\proxy_pack\$Proxy0.class
            File exactClassFile = new File(this.classPathFile, name.replaceAll("\\.", "/") + ".class");
            if (!exactClassFile.exists()) return null;

            inputStream = new FileInputStream(exactClassFile);
            byteArrayOutputStream = new ByteArrayOutputStream();

            final byte[] bytesBuffer = new byte[1014];
            int len;
            while ( (len = inputStream.read(bytesBuffer)) != -1 ) {
                byteArrayOutputStream.write(bytesBuffer, 0, len);
            }
            return this.defineClass(
                    className,
                    byteArrayOutputStream.toByteArray(),
                    0,
                    byteArrayOutputStream.size()
            );
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }
}
